Skip to content

fix: handle Anthropic-style token reporting in cached billing#5

Merged
jhaynie merged 5 commits intomainfrom
task/aigateway-integration
Apr 13, 2026
Merged

fix: handle Anthropic-style token reporting in cached billing#5
jhaynie merged 5 commits intomainfrom
task/aigateway-integration

Conversation

@jhaynie
Copy link
Copy Markdown
Member

@jhaynie jhaynie commented Apr 13, 2026

Summary

Fixes a billing bug where Anthropic cache hits were incorrectly billed. Anthropic reports input_tokens as non-cached only, while OpenAI includes cached tokens in prompt_tokens. The previous code clamped cached tokens to prompt tokens, which collapsed 2022 cached tokens down to 3.

The Bug

Anthropic response: input_tokens=3, cache_read_input_tokens=2022
Previous behavior:  cachedTokens=2022, clamp to promptTokens=3 → cachedTokens=3  ❌
Fixed behavior:     cachedTokens=2022, nonCached=3, total=2025                    ✅

Fix

CalculateCost now detects the reporting style:

  • cachedTokens <= promptTokens → OpenAI style (prompt includes cached) → nonCached = prompt - cached
  • cachedTokens > promptTokens → Anthropic style (prompt is non-cached only) → nonCached = prompt, adjust total

Tests Updated

  • TestCalculateCost_WithAnthropicCacheHit — real-world values (input_tokens=3, cache_read=2022)
  • TestCalculateCost_CacheExceedsPromptTokens_AnthropicStyle — verifies PromptTokens adjusted to true total

jhaynie added 5 commits April 12, 2026 23:11
CalculateCost now accepts CacheUsage and bills cached tokens at the
CacheRead rate instead of the full Input rate. This correctly reflects
the cost savings from prompt caching (typically 50-90% cheaper).

Changes:
- BillingResult: added CachedTokens and CachedInputCost fields
- CalculateCost: accepts *CacheUsage, splits cached/non-cached pricing
- BillingInterceptor: extracts cache_usage from ResponseMetadata.Custom
  and passes it to CalculateCost
Tests cover:
- No cache usage (nil) — all tokens at full rate
- OpenAI cache hit (CachedTokens field)
- Anthropic cache hit (CacheReadInputTokens field)
- Cache usage present but zero tokens — treated as no caching
- Cached tokens exceeding prompt tokens — clamped
- No CacheRead price — falls back to full input rate
- All tokens cached — zero non-cached cost
- Zero tokens — zero cost
- Mixed provider cache fields (summed)
- Interceptor extracting cache_usage from ResponseMetadata.Custom
- Interceptor with nil/empty Custom map
…es cached

Anthropic reports input_tokens as non-cached only, while OpenAI includes cached
tokens in prompt_tokens. CalculateCost now detects the style by comparing:
if cachedTokens > promptTokens, the provider is reporting non-cached only,
and promptTokens is adjusted to reflect the true total.

Fixes incorrect billing where Anthropic cache hits were clamped to
the small input_tokens count instead of reflecting the full cached amount.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 13, 2026

Warning

Rate limit exceeded

@jhaynie has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 4 minutes and 6 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 4 minutes and 6 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5d601731-88c1-4b64-804e-c7131e348ab6

📥 Commits

Reviewing files that changed from the base of the PR and between 12ae01a and 4d514cf.

📒 Files selected for processing (2)
  • billing.go
  • billing_test.go

Comment @coderabbitai help to get the list of available commands and usage tips.

@jhaynie jhaynie merged commit e1eebce into main Apr 13, 2026
2 checks passed
@jhaynie jhaynie deleted the task/aigateway-integration branch April 13, 2026 04:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant